
package com.example.testutil.util.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
/*
 * 进行Object 序列化和反序列化
 * 
 */
public class SerializableObjUtil {
    public static void SavaObject(Object obj, String path, String name) {
        File mFiles = new File(path);
        if (!mFiles.exists()) {
            mFiles.mkdirs();
        }
        File mFile = new File(mFiles, name);
        FileOutputStream mOutputStream = null;
        ObjectOutputStream mObjectOutputStream = null;
        try {
            if (!mFile.exists()) {
                mFile.createNewFile();
            }
            mOutputStream = new FileOutputStream(mFile);
            mObjectOutputStream = new ObjectOutputStream(mOutputStream);
            mObjectOutputStream.writeObject(obj);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (mOutputStream != null) {
                    mOutputStream.close();
                }
                if (mObjectOutputStream != null) {
                    mObjectOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized Object parseObject(String path, String name) {
        File mFile = new File(path + "/" + name);
        if (!mFile.exists()) {
            return null;
        }
        Object mObject = null;
        FileInputStream mInputStream = null;
        ObjectInputStream mObjectInputStream = null;

        try {
            mInputStream = new FileInputStream(mFile);
            mObjectInputStream = new ObjectInputStream(mInputStream);
            mObject = (Object) mObjectInputStream.readObject();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (StreamCorruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (mInputStream != null) {
                    mInputStream.close();
                }
                if (mObjectInputStream != null) {
                    mObjectInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return mObject;
    }
}
